/**
 * 
 */
package com.base.myproject.client.busi.service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.tools.Command;
import com.base.myproject.client.tools.CommandFactory;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncGetModelDatas;
import com.base.myproject.client.tools.CommandSyncHasCcode;
import com.base.myproject.client.tools.CommandSyncPay;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.celleditor.BaseRadioGroup;
import com.extjs.gxt.ui.client.Style.ButtonScale;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.fx.FxConfig;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ToggleButton;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Label;

/**
 * 收钱对话框，主要负责服务类型 ServiceListingX的收款
 * 
 * @author Administrator 2010-1-26
 */
public class PaidDialog implements Listener<BaseEvent>, AsyncCallback<CommandSyncReturnObject>{

	String ccode, bcode, s_cardno, password;

	Dialog d = new Dialog();
	FormPanel formpanel = new FormPanel();

	TextField<String> f_s_cardno = new TextField<String>(); // 会员卡号
	TextField<String> f_s_cardno_password = new TextField<String>(); // 会员卡号
	ToggleButton autoCal = new ToggleButton();//自动计算 。默认自动，按下为手动。
	Html message = new Html("");
	// 注意以下变量名称用拼音命名
	NumberField xianjin = new NumberField();
	NumberField xiaofeiquan = new NumberField();
	double yingshou = 0;
	double yingshou_g = 0;
	Html yingshou_html = new Html();
	Html yingzhaohui = new Html();
	CheckBox shuaka = new CheckBox();
	
	
	NumberField payeditor = new NumberField();
	NumberField pay_undiscounteditor = new NumberField();
	
	NumberField pay_geditor = new NumberField();
	NumberField pay_g_undiscounteditor = new NumberField();
	
	Button autofill = new Button("自动");
	Button autogfill = new Button("自动商品折扣");
	
	String icode;
	BaseStore<BusiObject> store =null;
	
	
	int paidProperty =0;
	final int SERVICE_PAID_NO_CHECK_EQUALS = 1;//不强制检查，应收以及实际收款
	final int UNSHOW_UNDISCOUNT_COLUMNS = 2;//不显示折扣前的价格，
	public PaidDialog() {
		autoCal.setText("处于自动计算消费金额状态");
//		autoCal.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.calc24()));
		autoCal.setScale(ButtonScale.MEDIUM);
		autofill.addListener(Events.Select, getListener());
		autogfill.addListener(Events.Select, getListener());

		pay_g_undiscounteditor.addListener(Events.Changed, getListener());
		pay_geditor.addListener(Events.Changed, getListener());
		payeditor.addListener(Events.Changed, getListener());
		pay_undiscounteditor.addListener(Events.Changed, getListener());
		
		finacestore.addStoreListener(getStoreListener());
		
		autofill.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.autos16()));
		
		autogfill.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.autog16()));
	}
	
	public PaidDialog(int property)
	{
		this();
		this.paidProperty = property;
		
	}

	public int getPaidProperty() {
		return paidProperty;
	}

	public void setPaidProperty(int paidProperty) {
		this.paidProperty = paidProperty;
	}
	
	public void addPaidProperty(int paidProperty) {
		this.paidProperty = this.paidProperty | paidProperty;
	}

	public void show() {
		d.setWidth("100");

		d.setHeading("收银");
		formpanel.setBorders(false);
		formpanel.setLabelWidth(75);
		formpanel.setFieldWidth(120);
		formpanel.setHeaderVisible(false);
//		formpanel.add(new Html("三种付款方式，选择其一"));
		//yingshou_html.setHtml("应收金额：<b><a style='font-size:20pt'><font color='#ff0000'>" + yingshou+" 购买商品金额："+yingshou_g+"</font> </a></b>");
//		yingshou_html.setHtml("资金状况：");
		callast();
	//	yingzhaohui.setHtml("资金状况：");
		formpanel.add(yingshou_html);
		formpanel.add(yingzhaohui);
		xianjin.setFieldLabel("现金");
		xiaofeiquan.setFieldLabel("消费券");
		shuaka.setFieldLabel("刷银行卡");
		f_s_cardno.setFieldLabel("使用会员卡");
		f_s_cardno_password.setFieldLabel("会员卡密码");
		f_s_cardno_password.setPassword(true);
		f_s_cardno.addListener(Events.Change, this);

		//		
		// FieldSet fs1 = new FieldSet();
		// FieldSet fs2 = new FieldSet();
		// FieldSet fs3 = new FieldSet();

		// fs1.add(xianjin);
		// fs1.add(xiaofeiquan);
		
//		formpanel.add(new Html("<hr>1."));
//		formpanel.add(xianjin);
//		formpanel.add(xiaofeiquan);
//		formpanel.add(new Html("<hr>2."));
//		formpanel.add(shuaka);
		formpanel.add(new Html("<hr> 录入会员卡号和密码后，光标在<U>会员卡密码</U>里按<U>回车</U>会显示会员基本信息.<br />如果是非会员请直接在<U>会员卡密码</U>里按<U>回车</U>"));
		formpanel.add(f_s_cardno);
		formpanel.add(f_s_cardno_password);
		
		FormPanel fp = new FormPanel();
		fp.setHeaderVisible(false);
		TableLayout tl = new TableLayout(4);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setColspan(1);
		
		
		TableData td2 = new TableData();
		td2.setRowspan(1);
		td2.setColspan(2);
//		td2.setMargin(50);
//		td2.setPadding(10);
		fp.setLayout(tl);
		
		fp.add(new Label("会员卡号:"),td);
		fp.add(f_s_cardno,td);
		
		
		fp.add(new Label("密码:"),td);
		fp.add(f_s_cardno_password,td);
		autoCal.setStyleAttribute("margin-left", "5px");
		fp.add(autoCal,td2);
		fp.add(message,td2);
		
		formpanel.add(fp);
		//formpanel.add(message);

		f_s_cardno_password.setToolTip("录入后按“回车”");
		d.setButtons(Dialog.OKCANCEL);
		d.getButtonById(Dialog.OK).setText("确认收款");
		d.getButtonById(Dialog.CANCEL).setText("放弃");
		d.getButtonById(Dialog.CANCEL).addListener(Events.Select, this);
		d.getButtonById(Dialog.OK).addListener(Events.Select, this);

		// f_s_cardno_password.addListener(Events.Change, this);
		f_s_cardno_password.addListener(Events.KeyUp, this);
		f_s_cardno_password.addListener(Events.Blur, this);
		xianjin.addListener(Events.KeyUp, this);
		xiaofeiquan.addListener(Events.KeyUp, this);
		f_s_cardno.addListener(Events.KeyUp, this);
		autoCal.addListener(Events.Toggle, this);
		
		d.setSize(810,491);
		d.add(formpanel);
		d.add(createFinaceGrid());
		
//		HorizontalPanel h = new HorizontalPanel();
//		h.add(autofill);
//		h.add(autogfill);
//		d.setBottomComponent(h);
		d.setBlinkModal(true);
		d.setModal(true);
		d.show();
		d.setFocusWidget(f_s_cardno);
		//f_s_cardno.focus();
	}
	//采用多账户的方式
	BaseStore<BusiObject> finacestore = new BaseStore<BusiObject>();/*{
		 protected void afterEdit(Record record)
		  {
			  afterEdit(record,true);
			  System.out.println("eeeeeeeeeeeeee");
		  }
	};*/
	BaseGrid<BusiObject> fg;
	BaseGrid<BusiObject> createFinaceGrid() {
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

//		ColumnConfig C1 = new ColumnConfig("code", "code", 80);
//		columns.add(C1);
		ColumnConfig C2 = new ColumnConfig("name", "帐户", 80);
		columns.add(C2);
//		ColumnConfig C7 = new ColumnConfig("amount", "帐户名称", 100);
//		columns.add(C7);
		ColumnConfig C3 = new ColumnConfig("lastamount", "未付款前帐户余额", 80);
		columns.add(C3);
		ColumnConfig C8 = new ColumnConfig("pay", "服务款", 80);
		CellEditor c  = new CellEditor(payeditor);
		//payeditor.add
		//payeditor.addListener(Events.KeyUp, this);
		C8.setEditor(c);
		columns.add(C8);
		if((getPaidProperty() & UNSHOW_UNDISCOUNT_COLUMNS)!=UNSHOW_UNDISCOUNT_COLUMNS)
		{
		ColumnConfig C10 = new ColumnConfig("pay_undiscount", "服务款(折前)", 80);
		
		//pay_undiscounteditor.addListener(Events.KeyUp, this);
		C10.setEditor(new CellEditor(pay_undiscounteditor));
		columns.add(C10);
		}
		
		ColumnConfig C9 = new ColumnConfig("pay_g", "商品款", 80);
		CellEditor ceditor  = new CellEditor(pay_geditor);
		//payeditor.add
		//pay_geditor.addListener(Events.KeyUp, this);
		C9.setEditor(ceditor);
		
		columns.add(C9);
		if((getPaidProperty() & UNSHOW_UNDISCOUNT_COLUMNS)!=UNSHOW_UNDISCOUNT_COLUMNS)
		{
		ColumnConfig C11 = new ColumnConfig("pay_g_undiscount", "商品款(折前)", 80);
		
		//pay_geditor.addListener(Events.KeyUp, this);
		C11.setEditor(new CellEditor(pay_g_undiscounteditor));
		columns.add(C11);
		}
//		ColumnConfig C4 = new ColumnConfig("finance", "帐户余额", 80);
//		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("s_discount", "服务折扣", 80);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("g_discount", "商品折扣", 80);
		columns.add(C6);
		ColumnModel cm  = null;
		if((getPaidProperty() & UNSHOW_UNDISCOUNT_COLUMNS)!=UNSHOW_UNDISCOUNT_COLUMNS)
		{
		 cm = new ColumnModel(columns)
		{
			 public String getColumnStyle(int colIndex) {
				 if(colIndex==3||colIndex==4||colIndex==5||colIndex==6)
				 {
					
					    return " background-color: #FFFF99;";
				 }
				
				    return configs.get(colIndex).getStyle();

				  }
		};
		}
		else
		{
			 cm = new ColumnModel(columns)
			{
				 public String getColumnStyle(int colIndex) {
					 if(colIndex==4||colIndex==5)
					 {
						
						    return " background-color: #FFFF99;";
					 }
					
					    return configs.get(colIndex).getStyle();

					  }
			};
		}
		 fg = new BaseGrid<BusiObject>(finacestore, cm, false, false);
		
		 cbs.setSelectionMode(SelectionMode.SINGLE);
		 fg.setSelectionModel(cbs);
		fg.setHeight(195);
		fg.setWidth(800);
		fg.getView().setForceFit(true);
		fg.addListener(Events.AfterEdit, getListener());
//		fg.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<BusiObject>(){});
		fg.getSelectionModel().addListener(Events.SelectionChange, getListener());
		return fg;
	}

	public NumberField getXianjin() {
		return xianjin;
	}

	public void setXianjin(NumberField xianjin) {
		this.xianjin = xianjin;
	}

	public NumberField getXiaofeiquan() {
		return xiaofeiquan;
	}

	public void setXiaofeiquan(NumberField xiaofeiquan) {
		this.xiaofeiquan = xiaofeiquan;
	}

	public CheckBox getShuaka() {
		return shuaka;
	}

	public void setShuaka(CheckBox shuaka) {
		this.shuaka = shuaka;
	}
	
	

	public double getYingshou() {
		return yingshou;
	}

	public void setYingshou(double yingshou) {
		this.yingshou = yingshou;
	}

	public double getYingshou_g() {
		return yingshou_g;
	}

	public void setYingshou_g(double yingshouG) {
		yingshou_g = yingshouG;
	}

	public String getCcode() {
		return ccode;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public String getBcode() {
		return bcode;
	}

	public void setBcode(String bcode) {
		this.bcode = bcode;
	}

	public String getS_cardno() {
		return f_s_cardno.getValue();
	}



	public String getPassword() {
		return f_s_cardno_password.getValue();
	}


	@Override
	public void handleEvent(BaseEvent be) {
		if (be.getType() == Events.Select) {
			if (be.getSource() == d.getButtonById(Dialog.OK)) {
				d.getButtonById(Dialog.OK).setEnabled(false);
				onOK();

			} else if (be.getSource() == d.getButtonById(Dialog.CANCEL)) {
				close();
			}
			
			
			
		}

		else if (be.getType() == Events.Blur) {
			if (be.getSource().equals(f_s_cardno_password))
					{
				//getuserAccount();
					}
		}
		else if(be.getType() == Events.Toggle)
		{
			GWT.log("is pressed="+autoCal.isPressed());
			if(autoCal.isPressed())
			{
				autoCal.setText("处于手动计算消费金额状态");
			//	autoCal.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.manual24()));
				autoCal.setToolTip("消费金额由人工录入，请按照实际情况在黄色部分录入金额");
				
			}
			else
			{
				autoCal.setText("处于自动计算消费金额状态");	
				autoCal.removeToolTip();
//				autoCal.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.calc24()));
			}
		}
		// 录入会员卡号，密码处点击回车回出现的信息，首先检查密码是否正确，再提示用户基本信息
		else if (be.getType() == Events.KeyUp) {

			if (be.getSource().equals(xianjin)
					|| be.getSource().equals(xiaofeiquan)) {

				// yingshou

				double d1 = xianjin.getValue() == null ? 0.00 : xianjin
						.getValue().doubleValue();

				double d2 = xiaofeiquan.getValue() == null ? 0.00 : xiaofeiquan
						.getValue().doubleValue();

				callast();
			}
			
			else if (be.getSource().equals(f_s_cardno)) {
				if (((ComponentEvent) be).getKeyCode() == 13|| ((ComponentEvent) be).getKeyCode() == 10 )
						{
					GWT.log("focus", null);
					f_s_cardno_password.focus();
						}
			}
			else if (be.getSource().equals(f_s_cardno_password)) {
				if (((ComponentEvent) be).getKeyCode() == 13
						|| ((ComponentEvent) be).getKeyCode() == 10) {
					getuserAccount();
				}
			}
		}

	}
	/**
	 * 获取用户帐号，前提是录入了用户的卡号和密码；
	 */
	void getuserAccount()
	{
		

		
		com.base.myproject.client.tools.Command c1 = new com.base.myproject.client.tools.Command() {
			public void Start() {
				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.checkhasCcode_scardno(f_s_cardno
						.getValue(),
						f_s_cardno_password.getValue(),
						new AsyncCallback<Boolean>() {
							public void onFailure(Throwable caught) {

								Complete();
								MessageBox
										.alert(
												"提示",
												"保存失败。\n网络连接失败!请稍候...\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。",
												null);
							}

							public void onSuccess(Boolean b) {
								Complete();
								if (b) {

									final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
											.create(com.base.myproject.client.tools.GreetingService.class);
									greetingService
											.getAssociator(
													f_s_cardno
															.getValue(),
													4,
													new AsyncCallback<Associator>() {

														@Override
														public void onFailure(
																Throwable caught) {
															MessageBox
																	.alert(
																			"提示",
																			"保存失败。\n网络连接失败!请稍候...\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。",
																			null);

														}

														@Override
														public void onSuccess(
																Associator result) {
															message
																	.setHtml("会员名称："
																			+ result
																					.getName()
																			+ "  会员电话："
																			+ result
																					.getPhone());
//																			+ "  剩余金额（不包括本次消费）"
//																			+ result
//																					.getFinance());
															// formpanel.add(new
															// Html("会员名称："+result.getName()
															// +"会员电话："+result.getPhone()+" 剩余金额（不包括本次消费）"+result.getFinance()));
															// formpanel.layout();

														}

													});
								}
								else if(f_s_cardno.getValue()==null && f_s_cardno_password.getValue()==null)
								{
									message
									.setHtml("临时客户");
								}
								else {
									Info.display("", "会员卡号或密码录入错误",
											"");
								}
							}
						});

			}
		};
		CommandFactory.addCommand(c1);
		CommandFactory.addCommand(getFinance());
	
	}
	/**
	 * 计算某一选中行
	 * mode 1,录入折扣计算非折扣
	 * mode 2，录入非折扣计算折扣
	 */
	void calRow(int row ,int mode)
	{
		NumberFormat  activeFormat = NumberFormat.getFormat("#.00");
		double lastamount = Double.parseDouble(fg.getStore().getValue(row,"lastamount").toString());
		double pay = Double.parseDouble(fg.getStore().getValue(row,"pay")==null?"0":fg.getStore().getValue(row,"pay").toString());
		double pay_g = Double.parseDouble(fg.getStore().getValue(row,"pay_g")==null?"0":fg.getStore().getValue(row,"pay_g").toString());
		
		double pay_undiscount = Double.parseDouble(fg.getStore().getValue(row,"pay_undiscount")==null?"0":fg.getStore().getValue(row,"pay_undiscount").toString());
		double pay_g_undiscount = Double.parseDouble(fg.getStore().getValue(row,"pay_g_undiscount")==null?"0":fg.getStore().getValue(row,"pay_g_undiscount").toString());
		double s_discount = Double.parseDouble(fg.getStore().getValue(row,"s_discount")==null?"0":fg.getStore().getValue(row,"s_discount").toString());
		double g_discount = Double.parseDouble(fg.getStore().getValue(row,"g_discount")==null?"0":fg.getStore().getValue(row,"g_discount").toString());
		//计算折扣
		if(mode==2)
		{
			GWT.log("pay_undiscount = "+pay_undiscount+" s_discount = "+s_discount);
		fg.getStore().setValue(row,"pay", activeFormat.format(pay_undiscount*s_discount*0.1));
		fg.getStore().setValue(row,"pay_g", activeFormat.format(pay_g_undiscount*g_discount*0.1));
		}
		//计算非折扣
		else if(mode==1)
			
		{
			GWT.log("pay="+ pay +" s_discount = "+s_discount );
		fg.getStore().setValue(row,"pay_undiscount", activeFormat.format(pay/(s_discount*0.1)));
		fg.getStore().setValue(row,"pay_g_undiscount", activeFormat.format(pay_g/(g_discount*0.1)));
		}
		
		 pay = Double.parseDouble(fg.getStore().getValue(row,"pay")==null?"0":fg.getStore().getValue(row,"pay").toString());
		 pay_g = Double.parseDouble(fg.getStore().getValue(row,"pay_g")==null?"0":fg.getStore().getValue(row,"pay_g").toString());
		 callast();
		fg.getStore().setValue(row,"finance", activeFormat.format(lastamount-pay-pay_g));
	}
	/**
	 * 计算全部金额，录入金额
	 * 返回true则可以提交，否则不能提交
	 * @return
	 */
	boolean calALL()
	{
		
		
		String errormessage="";
		 boolean b= true;
		double pay_undiscount=0.00;
		double pay_g_undiscount=0.00;
		for(int i=0;i<finacestore.getCount();i++)
		{
			
			
			pay_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_undiscount")==null?"0":fg.getStore().getValue(i,"pay_undiscount").toString());
			pay_g_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_g_undiscount")==null?"0":fg.getStore().getValue(i,"pay_g_undiscount").toString());
			
			
		}
	
		
		if(pay_undiscount-yingshou>0.01 ||pay_undiscount-yingshou<-0.01)
		{
//			MessageBox.alert("","服务款:"+pay_undiscount+"不等于应收："+yingshou,null);
//		
//			return false;
			
			errormessage+="\n实收服务款（折扣前）:"+pay_undiscount+"不等于应收："+yingshou ;
			b=false;
		
			
		}
		
		if(pay_g_undiscount-yingshou_g>0.01 || pay_g_undiscount-yingshou_g<-0.01)
		{
//			MessageBox.alert("","购买商品款:"+pay_g_undiscount+"不等于应收："+yingshou_g,null);
//			return false;
			errormessage+="\n实收购买商品款（折扣前）:"+pay_g_undiscount+"不等于应收："+yingshou_g;
			b=false;
		}
		
		double all = /*(xianjin.getValue()==null?0:xianjin.getValue().doubleValue())+*/pay_undiscount+pay_g_undiscount;
		if(all-yingshou-yingshou_g>1 )
		{
			
//			MessageBox.alert("","应收款:"+yingshou+"与"+yingshou_g+"不能于账户扣款："+all,null);
//			return false;
			
			errormessage+="\n应收款:"+yingshou+"与"+yingshou_g+"不等于账户扣款："+all;
			b=false;
		}
		if( all-yingshou-yingshou_g<-1)
		{ 
//			MessageBox.alert("","应收款:"+yingshou+"与"+yingshou_g+"不能于账户扣款："+all,null);
//			return false;
			errormessage+="\n应收款:"+yingshou+"与"+yingshou_g+"不等于账户扣款："+all;
			b=false;
		}
		
		
		if(errormessage.equals(""))
			return b;
		else
		{
			
			if((getPaidProperty() & SERVICE_PAID_NO_CHECK_EQUALS)==SERVICE_PAID_NO_CHECK_EQUALS)
			{
//				MessageBox box = MessageBox.confirm("警告",, new Listener<MessageBoxEvent>(){
//
//					@Override
//					public void handleEvent(MessageBoxEvent be) {
//						if(be.isCancelled())
//						{
//							//return false;
//						}
//						else
//						{
//							//b=false;
//						}
//						
//					}
//					
//					
//				});
				if(Window.confirm(errormessage+"\n 是否继续？"))
				{
					return true;
				}
				else
				{
					return false;
				}
				
			}
			else
			{
				MessageBox.alert("警告",errormessage+"\n不允许收款",null);
				return b;
			}
		}
		
	}
	/**
	 * 计算剩余金额
	 * 应付-账户扣款-现金付款
	 */
	double callast()
	{
		NumberFormat  activeFormat = NumberFormat.getFormat("#.00");
		
		double pay_undiscount=0.00;
		double pay_g_undiscount=0.00;
		for(int i=0;i<finacestore.getCount();i++)
		{
			
			
			pay_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_undiscount")==null?"0":fg.getStore().getValue(i,"pay_undiscount").toString());
			pay_g_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_g_undiscount")==null?"0":fg.getStore().getValue(i,"pay_g_undiscount").toString());
			
			
		}
		double all = /*(xianjin.getValue()==null?0:xianjin.getValue().doubleValue())+*/pay_undiscount+pay_g_undiscount;
		
//		yingzhaohui.setHtml("资金状况 服务:<b><a style='font-size:20pt'>" +
//				"<font color='#ff0000'>" + activeFormat.format((pay_undiscount - yingshou))+"</font> </a></b> " +
//						"商品购买:<b><a style='font-size:20pt'><font color='#ff0000'>" + activeFormat.format((pay_g_undiscount - yingshou_g))+"</font> </a></b>" +
//								"总余额:<b><a style='font-size:20pt'><font color='#ff0000'>" + activeFormat.format((all-yingshou-yingshou_g))+"</font> </a></b>");

		String html="";
		html += "<table cellspacing='0' width='400'>";
		html += "<tr>";
		html += "<td width='180' align='right'></td>";
		html += "<td width='180' align='right'>服务款</td>";
		html += "<td width='180' align='right'>购买商品</td>";
		html += "<td width='180' align='right'>&nbsp;&nbsp;余额</td>";
		html += "</tr>";
		
		html += "<tr>";
		html += "<td>应收:</td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((yingshou))+"</font> </a></b></td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((yingshou_g))+"</font> </a></b></td>";
		html += "<td align='right'></td>";
		

		html += "</tr>";
		
		html += "<tr>";
		html += "<td>已经付<b><a style='font-size:16pt;'><font color='#ff0000'> - ： </font> </a></b></td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((pay_undiscount))+"</font> </a></b></td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((pay_g_undiscount ))+"</font> </a></b></td>";
		html += "<td align='right'></td>";
		

		html += "</tr>";
		html += "<tr>";
		html += "<td>剩余：</td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((yingshou-pay_undiscount ))+"</font> </a></b></td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((yingshou_g-pay_g_undiscount ))+"</font> </a></b></td>";
		html += "<td align='right'><b><a style='font-size:16pt;'><font color='#ff0000'> "+activeFormat.format((yingshou+yingshou_g-all))+"</font> </a></b></td>";
		html += "</tr>";
		html += "</table>";
		yingzhaohui.setHtml(html);

		return all-yingshou-yingshou_g;
	}
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				
				try {
					if (sync == 1)
					{
						if (be.getType() == Events.Select) {
							if (be.getSource().equals("按钮变量")) {

							}
							else if (be.getSource().equals(autofill)) {
								
								autoFillService();
							}
							else if (be.getSource().equals(autogfill)) {
						
								autoFillGcodeservice();
								
							}
						} else if (be.getType() == Events.Changed) {
							   
							if (be.getSource().equals(pay_g_undiscounteditor) 
									
									||be.getSource().equals(pay_undiscounteditor)  ) {
							//	calRow(2);
								

							}
							if (be.getSource().equals(pay_geditor)
									||be.getSource().equals(payeditor) 
									  ) {
							//	calRow(1);
								
								
							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
						else if(be.getType()==Events.Update)
						{
							System.out.println("be.source1"+be.getSource());
							if (be.getSource() instanceof BaseStore) {
								
								System.out.println("be.source2"+be.getSource());
							}
						}
						else if (be.getType() == Events.AfterEdit) {
							
							 GridEvent<BusiObject> be2 = (GridEvent<BusiObject>)be;
							 
							 int index = be2.getRowIndex();
							 System.out.println("be2.getProperty()="+be2.getProperty());
							 System.out.println("index = "+index);
							 System.out.println(""+be2.getValue()+"startValue="+be2.getStartValue());
						//	if (!be2.getValue().equals(be2.getStartValue()))
							{
								
								if (be2.getProperty().equals("pay_undiscount")
										|| be2.getProperty().equals(
												"pay_g_undiscount")) {
									calRow(index,2);
								} else if (be2.getProperty().equals("pay")
										|| be2.getProperty().equals("pay_g")) {
									calRow(index,1);
								}
							}
							 
						}
						else if(be.getType() == Events.SelectionChange)
						{
							//手动
							if(!autoCal.isPressed())
							{
							GWT.log(""+fg.getSelectionModel().getSelectedItem());
							GWT.log(""+fg.getSelectionModel().getSelectedItems().size());
							GWT.log("grid selected");
							//先清空
							clearInput();
							autoFillService();
							autoFillGcodeservice();
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}
	Command getFinance()
	{
		Command c1 = new Command() {
			public void Start() {

				CommandSyncContainer list = new CommandSyncContainer();
				CommandSyncHasCcode chs = new CommandSyncHasCcode();
				
				chs.setS_cardno((f_s_cardno.getValue()==null)?"99999999":f_s_cardno.getValue());
				chs.setPassword(f_s_cardno_password.getValue());
				chs.setContinueorrollback(false);//跳出
				
				CommandSyncGetModelDatas csgmd = new CommandSyncGetModelDatas();
				csgmd.setSqlname("s_finace_acc");
			
				if(f_s_cardno.getValue()==null)
				{
				csgmd.putmacro("SCARDNO", "99999999");
				}
				else
				{
					csgmd.putmacro("SCARDNO", f_s_cardno.getValue());
				}
				list.add(chs);
				list.add(csgmd);
				final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
						.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService
						.SendCommandSync(
								list,
								new AsyncCallback<CommandSyncReturnObject>() {

									@Override
									public void onFailure(
											Throwable caught) {
										Complete();
										MessageBox.alert("错误",
												"网络连接失败", null);

									}

									@Override
									public void onSuccess(
											CommandSyncReturnObject result) {
										Complete();
										if (result.isB()) {
											// BaseStore<BusiObject>
											// salarystore = new
											// BaseStore<BusiObject>();
											if (result
													.getCommandsync() instanceof CommandSyncGetModelDatas) {
												// salarystore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
												// System.out.println(salarystore.getCount());
												System.out.println(((CommandSyncGetModelDatas)(result.getCommandsync())).getList());
											
												finacestore.removeAll();
												finacestore.add(((CommandSyncGetModelDatas)(result.getCommandsync())).getList(),false);
												autoall();
												fg.el().fadeIn(FxConfig.NONE);
												
											}

										} else {
											MessageBox
													.alert(
															"错误",
															"错误未知！"
																	+ result
																			.getMessage(),
															null);
											finacestore.removeAll();
											fg.el().fadeIn(FxConfig.NONE);
										}

									}

								});
			
			}
		};
		return c1;
	}
	/**
	 * 根据最近余额判断录入
	 */
	void autoall()
	{
		
		
		int row = 0;
		boolean flag = false;
		for(BusiObject bo:finacestore.getModels())
		{
			if(bo.get("lastamount")!=null)
			{
				finacestore.gotorow(row++);
				if(getYingshou_g()+getYingshou() < Double.parseDouble(bo.get("lastamount")+""))
				{
					autoFillService();
					autoFillGcodeservice();
					flag = true;
					break;
				}
			}
		}
		//如果找不到打折，就用第一行进行付款
		if(!flag)
		{
			finacestore.gotorow(0);
			NumberFormat  activeFormat = NumberFormat.getFormat("#.00");
			fg.getStore().setValue("pay_g", activeFormat.format(getYingshou_g()));
			fg.getStore().setValue("pay", activeFormat.format(getYingshou()));
			calRow(fg.getStore().getCurcowindex(),1);
		}
		
	}
	//自动录入服务款
	void autoFillService()
	{
		double lastamount = Double.parseDouble(fg.getStore().getValue("lastamount").toString());
		double s_discount = Double.parseDouble(fg.getStore().getValue("s_discount").toString());
		String accountcode = fg.getStore().getValue("code").toString();
		boolean SystemAccount = false;
		//s开头为系统帐户，不提示
		if(accountcode.toLowerCase().startsWith("s"))
		{
			SystemAccount =true;
		}
		if(!SystemAccount)
		if(lastamount<=0)
		{
			MessageBox.alert("警告", "此帐户无余额", null);
		}
		GWT.log(""+lastamount/(s_discount*0.1));
		NumberFormat  activeFormat = NumberFormat.getFormat("#.00");
		GWT.log(""+activeFormat.parse(lastamount/(s_discount*0.1)+""));
		GWT.log(""+activeFormat.format(lastamount/(s_discount*0.1)));
		//不是系统帐户，判断余额
		if (!SystemAccount) {
			if (yingshou > lastamount / (s_discount * 0.1)) {

				fg.getStore().setValue("pay",
						activeFormat.format(lastamount / (s_discount * 0.1)));
			} else {
				fg.getStore().setValue("pay",
						activeFormat.format(yingshou * (s_discount * 0.1)));
			}
		} else {
			fg.getStore().setValue("pay",
					activeFormat.format(yingshou * (s_discount * 0.1)));
		}
		calRow(fg.getStore().getCurcowindex(),1);
	}
	/**
	 * 自动录入商品款
	 */
	void autoFillGcodeservice()
	{
		double lastamount = Double.parseDouble(fg.getStore().getValue("lastamount").toString());
		double g_discount = Double.parseDouble(fg.getStore().getValue("g_discount").toString());
		String accountcode = fg.getStore().getValue("code").toString();
		boolean SystemAccount = false;
		//s开头为系统帐户，不提示
		if(accountcode.toLowerCase().startsWith("s"))
		{
			SystemAccount =true;
		}
		if(!SystemAccount)
		if(lastamount<=0)
		{
			MessageBox.alert("警告", "此帐户无余额", null);
		}
		GWT.log(""+lastamount/(g_discount*0.1));
		NumberFormat  activeFormat = NumberFormat.getFormat("#.00");
		GWT.log(""+activeFormat.parse(lastamount/(g_discount*0.1)+""));
		GWT.log(""+activeFormat.format(lastamount/(g_discount*0.1)));
		if(!SystemAccount)
		{
		if(yingshou_g>lastamount/(g_discount*0.1))
		{
			
			fg.getStore().setValue("pay_g", activeFormat.format(lastamount/(g_discount*0.1)));
		}
		else
		{
			fg.getStore().setValue("pay_g", activeFormat.format(yingshou_g*(g_discount*0.1)));
		}
		}
		//系统帐户，直接用金额
		else{
			fg.getStore().setValue("pay_g", activeFormat.format(yingshou_g*(g_discount*0.1)));
		}
		
		calRow(fg.getStore().getCurcowindex(),1);
	}
	/**
	 * 清空录入
	 */
	void clearInput()
	{
		
		for(int i=0;i<finacestore.getCount();i++)
		{
			
			
//			pay_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_undiscount")==null?"0":fg.getStore().getValue(i,"pay_undiscount").toString());
//			pay_g_undiscount+=Double.parseDouble(fg.getStore().getValue(i,"pay_g_undiscount")==null?"0":fg.getStore().getValue(i,"pay_g_undiscount").toString());
//			
			finacestore.setValue(i, "pay_undiscount", 0);
			finacestore.setValue(i, "pay_g", 0);
			finacestore.setValue(i, "pay", 0);
			finacestore.setValue(i, "pay_g_undiscount", 0);
		}
		callast();
	}
	
	StoreListener getStoreListener()
	{
		StoreListener sl = new StoreListener()
		{
			 public void storeUpdate(StoreEvent se) {
				 int sync = 0;
				 try{
					 sync++;
					 if (sync == 1)
					 {
						 System.out.println("------------");
						 //se.getRecord().
						// calRow(2);
					 }
				 }
				 finally
				 {
					 sync--;
				 }
			  }

		};
		return sl;
	}
	/**
	 * 付款成功，子类可以继承
	 */
	public void payaccountsuccess()
	{
		
	}
	
	/**
	 * 提交账户，检查并付款
	 */
	public void payaccount()
	{


		CommandSyncContainer list = new CommandSyncContainer();
		
//		CommandSyncHasCcode chs = new CommandSyncHasCcode();
//		
//		chs.setS_cardno((f_s_cardno.getValue()==null)?"99999999":f_s_cardno.getValue());
//		chs.setPassword(f_s_cardno_password.getValue());
//		chs.setContinueorrollback(false);//跳出
		
		CommandSyncPay csp = new CommandSyncPay();
		csp.setCcode((f_s_cardno.getValue()==null)?"99999999":f_s_cardno.getValue());
		csp.setPassword(f_s_cardno_password.getValue());
		csp.setMode(4);
		List<PayItem> paylist = new LinkedList<PayItem>();
		
		String s_cardno = f_s_cardno.getValue();
		for(int i=0;i<finacestore.getCount();i++)
		{
			
			double pay = Double.parseDouble(fg.getStore().getValue(i,"pay")==null?"0":fg.getStore().getValue(i,"pay").toString());
			double pay_g = Double.parseDouble(fg.getStore().getValue(i,"pay_g")==null?"0":fg.getStore().getValue(i,"pay_g").toString());
		
			if(pay>0||pay_g>0)

			{
			PayItem pi = new PayItem();
			pi.setAccountname(finacestore.getValue(i, "code").toString());
			pi.setNeedpay(true);
			pi.setPay(pay);
			pi.setPay_g(pay_g);
			pi.setS_cardno(s_cardno);
			pi.setUpicode(icode);
			
			paylist.add(pi);
			}
			
		}
		
		csp.setContinueorrollback(false);
		
		csp.setPaylist(paylist);
		
		
		
		CommandSyncsql commandsql = new CommandSyncsql();
		commandsql.getV().addAll(store._trySave(store.getCurcowindex()));
		
		
		String sql = "update s_service_po set busistatus='131072' where icode ='"
		+ icode + "'";
		commandsql.getV().add(sql);
	
	
		list.add(csp);
		list.add(commandsql);
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService
				.SendCommandSync(
						list,
						new AsyncCallback<CommandSyncReturnObject>() {

							@Override
							public void onFailure(
									Throwable caught) {
								d.getButtonById(Dialog.OK).setEnabled(true);
								MessageBox.alert("错误",
										"网络连接失败", null);
								
							}

							@Override
							public void onSuccess(
									CommandSyncReturnObject result) {
								
								if (result.isB()) {
									Info.display("", "提交成功");
									payaccountsuccess();
									

								} else {
									d.getButtonById(Dialog.OK).setEnabled(true);
									MessageBox
											.alert(
													"错误",
													""
															+ result
																	.getMessage(),
													null);
									
								}

							}

						});
	
	
	}
	
	/**
	 * 点ok的时候出发
	 */
	protected void onOK() {
		if(calALL())
		{
		payaccount();
		}
		else
		{
		d.getButtonById(Dialog.OK).setEnabled(true);
		}
//		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
//		.create(com.base.myproject.client.tools.GreetingService.class);
//greetingService.getAssociatorx("00001", 4, new AsyncCallback<AssociatorX>(){
//
//	@Override
//	public void onFailure(Throwable caught) {
//		// TODO Auto-generated method stub
//		
//	}
//
//	@Override
//	public void onSuccess(AssociatorX result) {
//		
//		
//		System.out.println(result.getCcode());
//		System.out.println(result.getMobil());
//		System.out.println(result.getName());
//		System.out.println(result.getS_cardno());
//		System.out.println(result.getPaylist());
//		for(PayItem pi:result.getPaylist())
//		{
//			System.out.println(pi.getAccountname());
//			System.out.println(pi.getLastamount());
//		}
//	}
//	
//});
		
	}

	/**
	 * 关闭
	 */
	public void close() {

		d.setVisible(false);
		formpanel = null;
		d = null;

	}

	@Override
	public void onFailure(Throwable caught) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSuccess(CommandSyncReturnObject result) {
		// TODO Auto-generated method stub
		
	}

	public String getIcode() {
		return icode;
	}
/**
 * 设置付款单据编码
 * @param icode
 */
	public void setIcode(String icode) {
		this.icode = icode;
	}

public BaseStore<BusiObject> getStore() {
	return store;
}

public void setStore(BaseStore<BusiObject> store) {
	this.store = store;
}

}
